package com.xxxx.transformation_operator;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;
import java.util.Random;

/**
 * @program: flink19Test
 * @description:
 * @author: CoreDao
 * @create: 2021-04-01 16:32
 **/

public class AggOperator {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<String> dataStreamSource = env.fromCollection(Arrays.asList("hello nihao","hello nihao2","hello ni"));

        dataStreamSource
                .flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] s = value.split(" ");
                        for (String s1 : s) {
                            Thread.sleep(1000);
                            int nextInt = new Random().nextInt(100);
                            System.out.println("key is" + s1 + "value is " + nextInt);
                            out.collect(Tuple2.of(s1,nextInt));
                        }
                    }
                })
                .map(new MapFunction<Tuple2<String, Integer>, Tuple2<String,Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
                        return value;
                    }
                })
                .keyBy(0)
                //基于key
                .max(1)
                /*
                key ishellovalue is 92
                (hello,92)
                key isnihaovalue is 54
                (nihao,54)
                key ishellovalue is 71
                (hello,92)
                key isnihao2value is 33
                (nihao2,33)
                key ishellovalue is 13
                (hello,92)
                key isnivalue is 58
                (ni,58)
                 */
                .print();


        env.execute();

    }
}
